var username, password;
var chirp = true;
var xml;
var postArray = new Array(3);
var pidgeon;
var refreshing = false;
var statusUrl="http://twitter.com/statuses/friends_timeline.json";
//var updateUrl="http://twitter.com/statuses/update.json";  <---------- THIS NO LONGER FUNCTIONS
var refreshTime = 2 * 60 * 1000;

var urlRegExp = /(^| )((http|https|mailto):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))/g;
var atRegExp = /(^| )@([a-z0-9_]+)/g;

function init(){
	username = System.Gadget.Settings.read("username");
	password = System.Gadget.Settings.read("password");
	chirp = System.Gadget.Settings.read("chirp");
	
	for (i=0; i<postArray.length; i++){
		postArray[i] = new Array(3);
		postArray[i][0] = gadgetBackground.addTextObject('','Segoe UI', 12, 'white', 95, 85 + i * 95);
		postArray[i][0].addGlow("black", 50, 50);
		postArray[i][1] = gadgetBackground.addImageObject("images/bubble.png", 20, 5 + i * 95);
		postArray[i][1].opacity=0;
	}
	if (username == ""){
		updatePost(2, "", "Please specify a username in settings", 0);
	}
	pidgeon = gadgetBackground.addImageObject("images/twitter.png", 68, 290);
	restartTimer();
}

var angle = 0;
var clockwise = true;
function animatePidgeon(){
	if (refreshing || (!refreshing && angle != 0)) {
		if (angle > 75){
			clockwise = false;
		} else if (angle < -40){
				clockwise = true;
		}
		
		if (clockwise){
			angle = angle + 1;
		} else {
			angle = angle - 1;
		}
		pidgeon.rotation = angle/5;
		//updatePost(3, "Debug", "angle = " + angle, 0);
		setTimeout(animatePidgeon, 40);
	}
}

function rightSize(characters){
	var rightSize = 10;
	
	if (characters <= 40){
		rightSize = 13;
	} else {
		if (characters <= 120){
			rightSize = 11;
		}
	}

	return rightSize + "px";
}

function updatePost(position, author, text, id){
	postArray[position-1][0].value = author;
	postArray[position-1][3] = id;
	postArray[position-1][1].opacity=100;
	document.getElementById("post" + position + "td").innerHTML = text.replace(urlRegExp,
                                       ' <a href="$2">$2</a>').replace(atRegExp,
                                                                       ' @<a href="http://twitter.com/$2">$2</a>');;
	document.getElementById("post" + position + "td").style.fontSize=rightSize(text.length);
}

function getWithAuth(url, callback) {
	xml = new XMLHttpRequest();
	xml.open("GET", url, true, username, password);
	xml.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xml.onreadystatechange = callback;
	xml.send("");
}

function fetchLatest(clear) {
	refreshing = true;
	animatePidgeon();
	//updatePost(2, "Gadgette", "Refreshing... Username: " + username +" Password: " + password, postArray[1][3]);

	getWithAuth(statusUrl, function(istimeout){
		if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
			data = jQuery.httpData(xml, "json");
			data = data.slice(0,3);

			var j = 1;
			var chirped = false;
			$.each(data, function() {
				if (chirp && !(this.id == postArray[j-1][3]) && !chirped){
					System.Sound.playSound("sounds/canary.wav");
					chirped = true;
				}
				updatePost(j, this.user.screen_name, this.text, this.id);
				j++;
			});
		} else {
			//updatePost(2, "Debug", "XMLReadyState: " + xml.readyState, 0);
		}
	});
	refreshing = false;
}

function restartTimer() {
    if (username != "") {
        fetchLatest(true);
		$(document).every(refreshTime, "refresh", function() {
            fetchLatest(false);
        });
    }
}

System.Gadget.settingsUI = "settings.html";
System.Gadget.onSettingsClosed = SettingsClosed;
//System.Gadget.onUndock = checkState;
//System.Gadget.onDock = checkState;
function SettingsClosed() {
	username = System.Gadget.Settings.read("username");
	password = System.Gadget.Settings.read("password");
	chirp = System.Gadget.Settings.read("chirp");
	restartTimer();
}

